<template>
  <div class="dashboard" style="padding: 20px">
    <el-skeleton v-if="loading" rows="6" animated />
    <template v-else>
      <el-row :gutter="24" class="stat-row">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card stat-card-hover">
            <div class="stat-header">
              <el-icon class="stat-icon"><User /></el-icon>
              <span class="stat-title">用户总数</span>
            </div>
            <el-statistic
              :value="outputData.weekUserCount"
              :value-style="{
                fontSize: '32px',
                fontWeight: 'bold',
                color: '#222',
                marginBottom: '8px',
                textAlign: 'center',
              }"
            >
              <template #suffix>
                <span class="stat-trend-label">周同比</span>
                <span :class="['stat-trend', trendClass(getTrend('user'))]">
                  {{ getTrendText("user") }}
                </span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card stat-card-hover">
            <div class="stat-header">
              <el-icon class="stat-icon"><ShoppingCart /></el-icon>
              <span class="stat-title">订单总数</span>
            </div>
            <el-statistic
              :value="outputData.weekOrderCount"
              :value-style="{
                fontSize: '32px',
                fontWeight: 'bold',
                color: '#222',
                marginBottom: '8px',
                textAlign: 'center',
              }"
            >
              <template #suffix>
                <span class="stat-trend-label">周同比</span>
                <span :class="['stat-trend', trendClass(getTrend('order'))]">
                  {{ getTrendText("order") }}
                </span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card stat-card-hover">
            <div class="stat-header">
              <el-icon class="stat-icon"><Money /></el-icon>
              <span class="stat-title">成交额</span>
            </div>
            <el-statistic
              :value="outputData.weekOrderMoney"
              :precision="2"
              prefix="¥"
              :value-style="{
                fontSize: '32px',
                fontWeight: 'bold',
                color: '#222',
                marginBottom: '8px',
                textAlign: 'center',
              }"
            >
              <template #suffix>
                <span class="stat-trend-label">周同比</span>
                <span :class="['stat-trend', trendClass(getTrend('money'))]">
                  {{ getTrendText("money") }}
                </span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card stat-card-hover">
            <div class="stat-header">
              <el-icon class="stat-icon"><ChatLineRound /></el-icon>
              <span class="stat-title">投诉数</span>
            </div>
            <el-statistic
              :value="outputData.weekComplaintCount"
              :value-style="{
                fontSize: '32px',
                fontWeight: 'bold',
                color: '#222',
                marginBottom: '8px',
                textAlign: 'center',
              }"
            >
              <template #suffix>
                <span class="stat-trend-label">周同比</span>
                <span :class="['stat-trend', trendClass(getTrend('complaint'))]">
                  {{ getTrendText("complaint") }}
                </span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>本周成交额趋势</span>
              </div>
            </template>
            <div ref="moneyChartRef" class="chart-placeholder"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>本周用户数分析</span>
              </div>
            </template>
            <div ref="userChartRef" class="chart-placeholder"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 最新动态 -->
      <el-card class="activity-card">
        <template #header>
          <div class="card-header">
            <span>系统动态</span>
          </div>
        </template>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in activities"
            :key="index"
            :timestamp="activity.timestamp"
            :type="activity.type"
          >
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </template>
  </div>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { User, ShoppingCart, Money, ChatLineRound } from "@element-plus/icons-vue";
import { getDashBoard, getDashBoardChart } from "@/api/dashboard";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import { TransitionPresets, useTransition } from "@vueuse/core";

const loading = ref(true);
const data = ref({
  weekUserCount: 0,
  lastWeekUserCount: 0,
  weekOrderCount: 0,
  lastWeekOrderCount: 0,
  weekOrderMoney: 0,
  lastWeekOrderMoney: 0,
  weekComplaintCount: 0,
  lastWeekComplaintCount: 0,
});

// 创建源数据ref
const sourceUserCount = ref(0);
const sourceOrderCount = ref(0);
const sourceOrderMoney = ref(0);
const sourceComplaintCount = ref(0);

// 创建过渡数据
const outputData = ref({
  weekUserCount: useTransition(sourceUserCount, {
    duration: 1000,
    transition: TransitionPresets.easeInOutCubic,
  }),
  weekOrderCount: useTransition(sourceOrderCount, {
    duration: 1000,
    transition: TransitionPresets.easeInOutCubic,
  }),
  weekOrderMoney: useTransition(sourceOrderMoney, {
    duration: 1000,
    transition: TransitionPresets.easeInOutCubic,
  }),
  weekComplaintCount: useTransition(sourceComplaintCount, {
    duration: 1000,
    transition: TransitionPresets.easeInOutCubic,
  }),
});

const moneyChartRef = ref(null);
const userChartRef = ref(null);

async function initCharts() {
  const res = await getDashBoardChart();
  if (!res.success) {
    return ElMessage.error(res.message);
  }

  // 通用图表配置
  const commonOptions = {
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#eee",
      borderWidth: 1,
      textStyle: {
        color: "#333",
      },
      axisPointer: {
        type: "shadow",
        shadowStyle: {
          color: "rgba(0, 0, 0, 0.03)",
        },
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "4%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      axisLine: {
        lineStyle: {
          color: "#ddd",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#666",
      },
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: "#eee",
          type: "dashed",
        },
      },
      axisLabel: {
        color: "#666",
      },
    },
  };

  // 成交额趋势图
  const moneyChart = echarts.init(moneyChartRef.value);
  const moneyOptions = {
    ...commonOptions,
    title: {
      left: "center",
      top: "10px",
      textStyle: {
        color: "#333",
        fontSize: 16,
        fontWeight: "normal",
      },
    },
    series: [
      {
        name: "成交额",
        type: "line",
        data: res.data.weekOrderMoneyList,
        smooth: true,
        symbol: "circle",
        symbolSize: 8,
        itemStyle: {
          color: "#409EFF",
        },
        lineStyle: {
          width: 3,
          color: "#409EFF",
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "rgba(64, 158, 255, 0.2)",
            },
            {
              offset: 1,
              color: "rgba(64, 158, 255, 0)",
            },
          ]),
        },
      },
    ],
  };
  moneyChart.setOption(moneyOptions);

  // 用户数分析图
  const userChart = echarts.init(userChartRef.value);
  const userOptions = {
    ...commonOptions,
    title: {
      left: "center",
      top: "10px",
      textStyle: {
        color: "#333",
        fontSize: 16,
        fontWeight: "normal",
      },
    },
    series: [
      {
        name: "用户数",
        type: "bar",
        data: res.data.weekUserCountList,
        barWidth: "40%",
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "#83bff6",
            },
            {
              offset: 0.5,
              color: "#409EFF",
            },
            {
              offset: 1,
              color: "#2e88ff",
            },
          ]),
          borderRadius: [4, 4, 0, 0],
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: "#66b1ff",
              },
              {
                offset: 0.7,
                color: "#409EFF",
              },
              {
                offset: 1,
                color: "#3a8ee6",
              },
            ]),
          },
        },
      },
    ],
  };
  userChart.setOption(userOptions);

  // 监听窗口大小变化，自动调整图表大小
  window.addEventListener("resize", () => {
    moneyChart.resize();
    userChart.resize();
  });
}

getDashBoard().then((res) => {
  if (res.success) {
    data.value = res.data;
    // 更新源数据，触发动画
    sourceUserCount.value = res.data.weekUserCount;
    sourceOrderCount.value = res.data.weekOrderCount;
    sourceOrderMoney.value = res.data.weekOrderMoney;
    sourceComplaintCount.value = res.data.weekComplaintCount;
  } else {
    ElMessage.error(res.message);
  }
  loading.value = false;
  nextTick(() => {
    initCharts();
  });
});

function getTrend(type) {
  if (type === "user") {
    if (data.value.lastWeekUserCount == 0) return 100;
    return ((data.value.weekUserCount - data.value.lastWeekUserCount) / data.value.lastWeekUserCount) * 100;
  }
  if (type === "order") {
    if (data.value.lastWeekOrderCount == 0) return 100;
    return ((data.value.weekOrderCount - data.value.lastWeekOrderCount) / data.value.lastWeekOrderCount) * 100;
  }
  if (type === "money") {
    if (data.value.lastWeekOrderMoney == 0) return 100;
    return ((data.value.weekOrderMoney - data.value.lastWeekOrderMoney) / data.value.lastWeekOrderMoney) * 100;
  }
  if (type === "complaint") {
    if (data.value.lastWeekComplaintCount == 0) return 100;
    return (
      ((data.value.weekComplaintCount - data.value.lastWeekComplaintCount) / data.value.lastWeekComplaintCount) * 100
    );
  }
  return 0;
}
function getTrendText(type) {
  const val = getTrend(type);
  return (val >= 0 ? "+" : "") + val.toFixed(2) + "%";
}
function trendClass(val) {
  return val >= 0 ? "up" : "down";
}

const activities = ref([
  {
    content: "新用户注册：张三",
    timestamp: "2024-01-20 10:00:00",
    type: "success",
  },
  {
    content: "新订单创建：#12345",
    timestamp: "2024-01-20 09:30:00",
    type: "primary",
  },
  {
    content: "库存预警：商品A库存不足",
    timestamp: "2024-01-20 09:00:00",
    type: "warning",
  },
  {
    content: "系统更新完成",
    timestamp: "2024-01-20 08:30:00",
    type: "info",
  },
]);
</script>

<style scoped>
.dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.stat-row {
  margin-bottom: 24px;
}
.stat-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  padding: 24px 16px 16px 16px;
  min-height: 160px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.stat-card-hover:hover {
  box-shadow: 0 4px 24px 0 rgba(64, 158, 255, 0.15);
}
.stat-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.stat-icon {
  font-size: 32px;
  color: #409eff;
  margin-right: 10px;
}
.stat-title {
  font-size: 18px;
  font-weight: 600;
  color: #222;
}
.stat-trend-label {
  color: #909399;
  font-size: 14px;
  margin-right: 8px;
}
.stat-trend {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  margin-left: 4px;
  background: #f6ffed;
  color: #67c23a;
}
.stat-trend.down {
  background: #fff1f0;
  color: #f56c6c;
}

/* 图表区域样式优化 */
.chart-row {
  margin-top: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  background: #fff;
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.chart-card :deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
  border-radius: 8px 8px 0 0;
}

.chart-placeholder {
  height: 350px;
  padding: 20px;
  background-color: #fff;
  border-radius: 0 0 8px 8px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header span {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

/* 系统动态样式 */
.activity-card {
  margin-top: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.activity-card :deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-timeline-item__node) {
  background-color: #409eff;
}

:deep(.el-timeline-item__content) {
  color: #606266;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
}
</style>
